<template>
	<view class="container">
		<!-- <hy-nav-bar title="用户管理" :background="{
			backgroundColor: 'rgba(0,0,0,0)'
		}" :border-bottom="false" :titleColor="'#000'" backIconColor="#000"></hy-nav-bar> -->
		<view class="tabs">
			<u-tabs :list="tabs" name="tabName" :is-scroll="false" v-model="currentTab" @change="tabChange"
				inactive-color="#666" active-color="#FF6C18"></u-tabs>
		</view>
		<swiper class="swiper" :current="currentTab" @change="swiperChange">
			<!-- 搜索 -->
			<u-search style="margin: 40rpx 0;" placeholder="搜索用户名" v-model="userWord" :show-action="false"
				action-text="搜索" :animation="true"></u-search>
			<swiper-item v-for="(tab, index) in tabs" :key="index">
				<scroll-view scroll-y="true" class="scroll-Y" @scrolltoupper="upper" @scrolltolower="lower"
					@scroll="scroll">
					<view class="list">
						<view class="userBox" v-for="(item, index) in tab.list" :key="index">
							<view class="avatar">
								<u-avatar :src="getImgFullPath(item?.userDetail?.avatar)" size="110"
									mode="circle"></u-avatar>
								<text class="name">{{ item?.user?.name === '未设置昵称' ? item?.user?.username.replace(
									/^(\d{3})\d*(\d{4})$/, '$1****$2') : item?.userDetail?.name }}</text>
							</view>
							<view class="content">
								<view class="actions">
									<!-- <text class="time">{{ dateFormat(new Date(item?.updateTime * 1000), 'yyyy-MM-dd hh:mm:ss')
										}}</text> -->

									<view class="btns">

										<u-button class="custom-style1" v-if="item.myFriend == 2"
											style="margin-right: 20rpx;" ripple @click="addContactor(item)">
											加好友</u-button>
										<u-button class="custom-style" v-else size="mini" ripple plain
											@click="toChat(item)">发消息</u-button>
									</view>
									<text class="active-time">{{ getActiveTime(item?.updateTime * 1000) }}</text>

									<!-- <text class="tips">{{ dateFormat(new Date(item?.createTime * 1000),'MM-dd')}} 活跃</text> -->
								</view>
							</view>
						</view>
						<u-empty v-if="!tab.list.length" text="暂无相关的用户" margin-top="160"></u-empty>

					</view>
				</scroll-view>
			</swiper-item>
		</swiper>
		<van-dialog v-model:show="show" title="添加好友" show-cancel-button :before-close="handleBeforeClose">
			<van-form>
				<van-cell-group inset>
					<van-cell-group inset>
						<van-field v-model="messageForm.msg" rows="2" autosize label="留言" type="textarea" maxlength="50"
							placeholder="打个招呼~" show-word-limit />
						<van-field v-model="messageForm.nickname" label="备注" placeholder="填写好友备注~" />
					</van-cell-group>
				</van-cell-group>

			</van-form>
		</van-dialog>
	</view>
</template>
<script setup lang="ts">
import { ref, reactive } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { socialApi } from '@/api';
import { getImgFullPath, dateFormat } from '@/utils';
import { route } from '@/utils/common';
import RongIMLib from '@/packageD/common/rongCloud/im_init';
import { useUserStore } from '@/store';
import { Dialog } from 'vant';
const userStore = useUserStore()
const userWord = ref()  //搜索用户名称
const messageForm = ref({
	msg: '',
	nickname: '',
	fromUserId: 0,
	status: 0,
	toUserId: 0,
})  //弹窗内容
const show = ref(false);
interface ItemOfList {
	user: {
		avatar: string
		nickname: string
		[key: string]: any
	}
	createTime: number
	[key: string]: any
}
interface ITab {
	tabName: string
	key?: string
	value?: string | number
	createTime?: number
	list: ItemOfList[]
	[key: string]: any
}
const tabs = reactive<ITab[]>([
	{
		tabName: '全部',
		list: []
	},
	{
		tabName: '已购买',
		matched: [{ purchaseStatus: 1 }],
		list: []
	},
	{
		tabName: '未购买',
		matched: [{ purchaseStatus: 0 }],
		list: []
	},
	// {
	// 	tabName: '未购-关注',
	// 	matched: [{ purchaseStatus: 0, followingStatus: 1 }],
	// 	list: []
	// },
	// {
	// 	tabName: '未购-点赞',
	// 	matched: [{ purchaseStatus: 0, likedStatus: 1 }],
	// 	list: []
	// },
	// {
	// 	tabName: '未购-入群',
	// 	matched: [{ purchaseStatus: 0, joinCircleStatus: 1 }],
	// 	list: []
	// }
])
const currentTab = ref(0)
const tabChange = (index: number) => {
	currentTab.value = index
}
const swiperChange = (e: any) => {
	currentTab.value = e.detail.current
}
const pagination = reactive({
	pageIndex: 1,
	pageSize: 30,
	finished: false
})
async function getData() {
	let { pageIndex, pageSize, finished } = pagination
	if (finished) return
	uni.showLoading({
		title: '加载中...',
		mask: true
	})
	const { data, current, pages } = await socialApi.getShopUserList({
		pageIndex,
		pageSize
	}).finally(() => {
		uni.hideLoading()
	})
	if (data.data && data.data.length) {
		tabs[0].list = data.data
	} else {
		tabs[0].list = []
	}
	if (currentTab.value !== 0) {
		tabs[currentTab.value].list = dataFilter(tabs[0].list, currentTab.value)
	} else {
		tabs.forEach((tab, index) => {
			tab.list = dataFilter(tabs[0].list, index)
		})
	}
	if (current < pages) {
		pageIndex++
	} else {
		finished = true
	}
}
function dataFilter(data: ItemOfList[], index: number): ItemOfList[] {
	const matcher = tabs[index].matched
	if (!matcher) return data
	const list = data.filter((item) => {
		return matcher.every((m: { [x: string]: any; }) => {
			return Object.keys(m).every((key) => {
				return item[key] === m[key]
			})
		})
	})
	return list
}
function upper() { }
function lower() {
	console.log('lower')
}
function scroll(e: any) {
	const { scrollTop } = e.detail
}
function scrollTop() {

}
function toChat(data: { userId: any; }) {
	route({
		url: '/packageD/pages/chat/index',
		params: {
			conversationType: RongIMLib.ConversationType.PRIVATE,
			userId: data.userId,
			targetId: data.userId
		}
	})
}
// 加好友
async function addContactor(item: any) {
	// uni.showLoading()
	// return
	// const { data } = await socialApi.addChatFriend(userStore.userInfo.id, addUserId).finally(() => {
	// 	uni.hideLoading()
	// })
	// uni.showToast({
	// 	title: '添加成功',
	// 	icon: 'success',
	// })
console.log(item, 'item');

	show.value = true;
	messageForm.value.fromUserId = userStore.userInfo.id
	messageForm.value.toUserId = item?.userId
	messageForm.value.msg = `我是${item.name}`
}
// 修复后的 before-close 处理函数
const handleBeforeClose = (action: string, done: (confirm: boolean) => void) => {
	console.log(action, 77);
	new Promise((resolve) => {
		if (action === 'confirm') {
			setTimeout(async () => {
				console.log(messageForm.value, '测试表单数据');
				const res = await socialApi.circleUserApplyAdd(messageForm.value)
				console.log(res, '提交成功',);
				if (res.code == 200) {
					show.value = false;
					messageForm.value = {
						msg: '',
						nickname: '',
						fromUserId: 0,
						status: 0,
						toUserId: 0,
					}
					getData()
					uni.showToast({
						title: '已发送',
						icon: 'success',
					})


				} else {
					Dialog.alert({
						title: '提示',
						message: res.msg,
					}).then(() => {
						show.value = true;
					});
				}
				resolve(true);
			}, 1000);
		} else {
			// 拦截取消操作
			show.value = false;
			resolve(false);
		}

	});
};

//提交好友申请
const addFriend = async () => {

}
//用户朋友关系列表
// const friendList = async () => {
// 	const { data } = await socialApi.friendList({
// 		noPaging: false
// 	})

// 	console.log(data, '获取到用户朋友');

// }

// 计算活跃时间
function getActiveTime(updateTime: number): string {
	const now = new Date().getTime();
	const diff = now - updateTime;
	const minutes = Math.floor(diff / (1000 * 60));
	const hours = Math.floor(diff / (1000 * 60 * 60));


	if (hours >= 24) {
		return '';
	} else if (hours >= 1) {
		return `${hours}小时前活跃`;
	} else {
		return `${minutes}分钟前活跃`;
	}
}



onLoad(() => {
	getData()
	// friendList()
})

</script>

<style lang="scss" scoped>
@import '@/styles/helper.scss';

.container {
	min-height: 100vh;
	background: #fff;

	.tabs {
		position: sticky;
		top: 0;
		// #ifdef H5
		top: calc(env(safe-area-inset-top));
		// #endif
		background: hsl(0, 0%, 100%);
		z-index: 2;
	}

	.swiper {
		padding: 0 20rpx;
		margin-top: 20rpx;
		height: calc(100vh - 80rpx - 44px);
		background-color: #fff;
	}

	.userBox {
		display: flex;
		justify-content: space-between;
		// width: 100%;
		padding: 20rpx;
		box-sizing: border-box;
		background: #fff;

		.avatar {
			display: flex;
			align-items: center;
			justify-content: center;

			.name {
				margin-left: 30rpx;
				font-size: 28rpx;
				max-width: 340rpx;
				@include ellipsis;
			}
		}

		.content {
			// flex: 1;
			margin-left: 20rpx;

			.actions {
				display: flex;
				// align-items: flex-end;
				flex-direction: column;
				// justify-content: flex-end;
				gap: 20rpx;
				text-align: center;
				width: 150rpx;
				// background-color: pink;

				.tips {
					color: #999;
				}

				.time {
					color: #999;
					text-align: center;
				}

				.active-time {
					color: #717171;
					font-size: 24rpx;
				}

				.custom-style {
					width: 150rpx;
					height: 48rpx;
					font-size: 26rpx;
					color: #ff6c18;
				}

				.custom-style1 {
					width: 150rpx;
					height: 52rpx;
					font-size: 26rpx;
					color: #fff;
					background-color: #ff6c18;
				}
			}
		}
	}
}
</style>
